package org.beaconframework.ext.rs.jersey;

import javax.ws.rs.ext.RuntimeDelegate;

import org.beaconframework.ext.rs.WebResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class WebResourceFactory implements
		org.beaconframework.ext.rs.WebResourceFactory, ApplicationContextAware {

	Logger log = LoggerFactory.getLogger(WebResourceFactory.class);
	ClientConfig clientConfig;
	String url;
	String username;
	String password;
	ApplicationContext applicationContext;
	
	public WebResourceFactory() {
		super();
		clientConfig = new DefaultClientConfig();
		checkRuntime();
	
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}
	
	
	protected void checkRuntime() {
		RuntimeDelegate delegate = RuntimeDelegate.getInstance();
		if (!delegate.getClass().getName().startsWith("com.sun.ws.rs")) {
			log.error("\n\n* * *  You are trying to use Jersey JAX-RS, but the installed runtime is showing as: "+delegate.getClass()+"\n* * * "+
					"You will almost certainly experience problems.\n\n");
		}
		else {
			log.info("JAX-RS RuntimeDelegate: {}",delegate);
		}
	}

	@Override
	public WebResource createWebResource() {
	
		Client client = null;
		client = Client.create(getClientConfig());
		
		if (getUsername() != null && getUsername().trim().length() > 0) {
			client.addFilter(new HTTPBasicAuthFilter(getUsername(),
					getPassword()));
		}
		if (getUrl()==null) {
			throw new NullPointerException("url must be set on WebResourceFactory");
		}
		com.sun.jersey.api.client.WebResource wr = client.resource(getUrl());
		return new WebResourceFacade(client,wr);

	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public ClientConfig getClientConfig() {
		return clientConfig;
	}

	public void setClientConfig(ClientConfig clientConfig) {
		this.clientConfig = clientConfig;
	}

}
